#include <iostream>
using namespace std;
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    RECV_ERROR,
    SENDTO_ERROR
};


const int defaultsockfd = -1;

class UdpServer
{
public:
    UdpServer(uint16_t port, string ip) :_sockfd(defaultsockfd), _port(port), _ip(ip), _isrunning(false)
    {}

    void InitServer()
    {
        // 1. 创建 socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            cout << "sock fail" << strerror(errno) << errno << endl;
            exit(SOCKET_ERROR);
        }
        cout << "socket make success, sockfd: " << _sockfd << endl;

        // 2. 填充 sockaddr_in
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(_port); // 主机序列 -> 网络序列 

        local.sin_addr.s_addr = inet_addr(_ip.c_str()); // 字符串风格的点分十进制 ip -> 4字节 ip

        // 3. bind 
        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if (n < 0)
        {
            cout << "socket bind error" << endl;
            exit(BIND_ERROR);
        }
        cout << "socket bind success" << endl;
    }

    void Start()
    {
        _isrunning = true;
        while (true)
        {
            // 1. 接受信息
            char buffer[1024];
            struct sockaddr_in peer;
            memset(buffer, 0, sizeof(buffer));
            socklen_t len = sizeof(peer);

            ssize_t n = recvfrom(_sockfd, buffer, 1024, 0, (struct sockaddr*)&peer, &len);
            if (n > 0)
            {
                buffer[n] = 0;
                cout << "get message# " << buffer << endl;

                // 2. 发送信息
                n = sendto(_sockfd, buffer, strlen(buffer), 0, (struct sockaddr*)&peer, len);
                if (n < 0)
                {
                    cout << "sendto error" << endl;
                    exit(SENDTO_ERROR);
                }
            }
            else if (n < 0)
            {
                cout << "recvfrom error" << endl;
                exit(RECV_ERROR);
            }
        }
        _isrunning = false;
    }

    ~UdpServer()
    {}
private:
    int _sockfd;
    uint16_t _port;
    string _ip;

    bool _isrunning;
};